package cn.edu.swu.miniwebsvr.core;

import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpParser {

    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

        try {
            // 1. 读取并解析 HTTP 请求行
            String requestLine = reader.readLine();
            if (requestLine == null || requestLine.isEmpty()) {
                // 返回一个基本的Parameter对象，避免null
                parameter.setMethod("GET");
                parameter.setUrl("/");
                return parameter;
            }

            System.out.println("Request Line: " + requestLine);

            String[] requestParts = requestLine.split("\\s+", 3); // 限制分割为3部分
            if (requestParts.length >= 2) {
                // 设置请求方法
                parameter.setMethod(requestParts[0].toUpperCase());

                // 解析URL和查询参数
                String url = requestParts[1];
                parseUrlAndParams(parameter, url);
            } else {
                // 如果请求行格式不正确，设置默认值
                parameter.setMethod("GET");
                parameter.setUrl("/");
                System.err.println("Invalid request line: " + requestLine);
            }

            // 2. 循环读取并解析所有 HTTP 请求头
            String headerLine;
            while ((headerLine = reader.readLine()) != null) {
                if (headerLine.isEmpty()) {
                    break;
                }

                int colonIndex = headerLine.indexOf(':');
                if (colonIndex > 0) {
                    String headerName = headerLine.substring(0, colonIndex).trim();
                    String headerValue = headerLine.substring(colonIndex + 1).trim();

                    parameter.addHeader(headerName, headerValue);
                }
            }

            // 3. 根据请求方法 (Method) 和请求头 (Content-Length, Content-Type) 判断并读取请求体
            if ("POST".equalsIgnoreCase(parameter.getMethod()) || "PUT".equalsIgnoreCase(parameter.getMethod())) {
                parseRequestBody(parameter, reader);
            }

            System.out.println("Parsed request: " + parameter.getMethod() + " " + parameter.getUrl());
            System.out.println("URL params: " + parameter.getUrlParams().size());
            System.out.println("Headers: " + parameter.getHeaders().size());

        } catch (Exception e) {
            System.err.println("Error parsing HTTP request: " + e.getMessage());
            e.printStackTrace();
            // 确保返回一个有效的Parameter对象
            if (parameter.getMethod() == null) {
                parameter.setMethod("GET");
            }
            if (parameter.getUrl() == null) {
                parameter.setUrl("/");
            }
        }

        return parameter;
    }

    /**
     * 解析URL和查询参数
     */
    private static void parseUrlAndParams(Parameter parameter, String url) {
        if (url == null || url.isEmpty()) {
            parameter.setUrl("/");
            return;
        }

        // 分离URL路径和查询参数
        int questionMarkIndex = url.indexOf('?');
        if (questionMarkIndex != -1) {
            // 设置URL路径部分
            String path = url.substring(0, questionMarkIndex);
            parameter.setUrl(path);

            // 解析查询参数
            String queryString = url.substring(questionMarkIndex + 1);
            parseQueryString(parameter.getUrlParams(), queryString);
        } else {
            parameter.setUrl(url);
        }
    }

    /**
     * 解析查询字符串（URL参数和请求体参数通用）
     */
    private static void parseQueryString(Map<String, String> params, String queryString) {
        if (queryString == null || queryString.isEmpty()) {
            return;
        }

        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            int equalsIndex = pair.indexOf('=');
            if (equalsIndex > 0) {
                try {
                    String key = URLDecoder.decode(pair.substring(0, equalsIndex), StandardCharsets.UTF_8.name());
                    String value = URLDecoder.decode(pair.substring(equalsIndex + 1), StandardCharsets.UTF_8.name());
                    params.put(key, value);
                } catch (Exception e) {
                    System.err.println("Error decoding parameter: " + pair);
                }
            } else if (!pair.isEmpty()) {
                try {
                    String key = URLDecoder.decode(pair, StandardCharsets.UTF_8.name());
                    params.put(key, "");
                } catch (Exception e) {
                    System.err.println("Error decoding parameter: " + pair);
                }
            }
        }
    }

    /**
     * 解析请求体
     */
    private static void parseRequestBody(Parameter parameter, BufferedReader reader) throws IOException {
        // 检查Content-Length
        String contentLengthHeader = parameter.getHeaders().get("Content-Length");
        String contentTypeHeader = parameter.getHeaders().get("Content-Type");

        if (contentLengthHeader != null) {
            try {
                int contentLength = Integer.parseInt(contentLengthHeader);
                if (contentLength > 0) {
                    char[] bodyChars = new char[contentLength];
                    int bytesRead = reader.read(bodyChars, 0, contentLength);
                    if (bytesRead > 0) {
                        String requestBody = new String(bodyChars, 0, bytesRead);
                        System.out.println("Request body: " + requestBody);

                        // 根据Content-Type解析请求体
                        if (contentTypeHeader != null && contentTypeHeader.contains("application/x-www-form-urlencoded")) {
                            // 表单数据
                            parseQueryString(parameter.getBodyParams(), requestBody);
                        } else if (contentTypeHeader != null && contentTypeHeader.contains("application/json")) {
                            // JSON数据，这里简单处理，实际可能需要JSON解析库
                            parameter.getBodyParams().put("json", requestBody);
                        } else {
                            // 其他类型，直接存储原始数据
                            parameter.getBodyParams().put("raw", requestBody);
                        }
                    }
                }
            } catch (NumberFormatException e) {
                System.err.println("Invalid Content-Length: " + contentLengthHeader);
            }
        }
    }

    /**
     * URL解码辅助方法
     */
    public static String urlDecode(String encoded) {
        try {
            return URLDecoder.decode(encoded, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            System.err.println("Error decoding: " + encoded);
            return encoded;
        }
    }

    /**
     * 解析键值对字符串的辅助方法
     */
    public static void parseKeyValueString(Map<String, String> map, String data, String pairSeparator, String keyValueSeparator) {
        if (data == null || data.isEmpty()) {
            return;
        }

        String[] pairs = data.split(pairSeparator);
        for (String pair : pairs) {
            String[] keyValue = pair.split(keyValueSeparator, 2);
            if (keyValue.length == 2) {
                map.put(urlDecode(keyValue[0].trim()), urlDecode(keyValue[1].trim()));
            } else if (keyValue.length == 1 && !keyValue[0].trim().isEmpty()) {
                map.put(urlDecode(keyValue[0].trim()), "");
            }
        }
    }
}